﻿using System;
using System.Collections.Generic;
using MdcService.Structure;
using MdcService.Structure.Enum;

namespace MdcService.Service
{
    public class ProcedureService:IService
    {
        private RunningContext _runningContext;

        public ProcedureService(RunningContext runningContext)
        {
            _runningContext = runningContext;
        }

        private IList<IService> StartProcedure { get;}= new List<IService>();
        private IList<IService> StopProcedure { get;} = new List<IService>();
        public event EventHandler<EventArgs> Started;
        public event EventHandler<EventArgs> Stopped;


        public void Start()
        {
            if (StartProcedure.Count>0)
            {
                StartProcedure[0].Start();
            }
        }

        public void Stop()
        {
            if (StopProcedure.Count > 0)
            {
                StopProcedure[0].Stop();
            }
        }

        public ProcedureService QueueStart(IService service)
        {
            service.Started += StartProcess;
            StartProcedure.Add(service);
            return this;
        }

        public ProcedureService QueueStop(IService service)
        {
            service.Stopped += StopProcess;
            StopProcedure.Add(service);
            return this;
        }

        private void StartProcess(object sender, EventArgs e)
        {
            var index = StartProcedure.IndexOf(sender as IService);
            if (index < StartProcedure.Count - 1)
            {
                StartProcedure[index + 1].Start();
            }
            else
            {
                Started?.Invoke(this,new EventArgs());
            }
        }

        private void StopProcess(object sender, EventArgs e)
        {
            var index = StopProcedure.IndexOf(sender as IService);
            if (index < StopProcedure.Count - 1)
            {
                StopProcedure[index + 1].Stop();
            }
            else
            {
                Stopped?.Invoke(this, new EventArgs());
            }
        }

    }
}
